#include "List.h"

ListNode* CreateLNode(x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return;
	}

	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;
	return newnode;
}

ListNode* InitList()
{
	ListNode* phead = CreateLNode(-1);
	phead->next = phead;
	phead->prev = phead;
	return phead;
}
void ListPrint(ListNode* phead)
{
	assert(phead);
	ListNode* cur = phead->next;
	printf("HEAD");
	while (cur != phead)
	{
		printf(" <=%d=> ", cur->data);
		cur = cur->next;
	}
	printf("\n");
}
void ListPushBack(ListNode* phead, LTDataType x)
{
	assert(phead);
	ListNode* newnode = CreateLNode(x);
	ListNode* tail = phead->prev;
	//phead    tail   newnode
	newnode->prev = tail;
	tail->next = newnode;
	newnode->next = phead;
	phead->prev = newnode;
}

void ListPopBack(ListNode* phead)
{
	assert(phead);
	assert(phead->next != phead);

	ListNode* tail = phead->prev;
	ListNode* tailprve = tail->prev;
	free(tail);
	tailprve->next = phead;
	phead->prev = tailprve;

}
void ListDestory(ListNode* phead)
{
	assert(phead);
	
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		ListNode* next = cur->next;
		free(cur);
		cur = next;
	}
		free(phead);
}
void ListPushFront(ListNode* phead, LTDataType x)
{
	assert(phead);
	struct ListNode* newnode = CreateLNode(x);
	//phead   newnode   phead->next
	phead->next->prev = newnode;
	newnode->next = phead->next;
	phead->next = newnode;
	newnode->prev = phead;
}

void ListPopFront(ListNode* phead)
{
	assert(phead);
	assert(phead->next != phead);
	struct ListNode* next = phead->next->next;
	free(phead->next);
	phead->next = next;
	next->prev = phead;
}

ListNode* ListFind(ListNode* phead, LTDataType x)
{
	assert(phead);
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void ListInsert(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* newnode = CreateLNode(x);

	ListNode* posprev = pos->prev;
	// posprev   newnode  pos 
	posprev->next = newnode;
	newnode->prev = posprev;
	newnode->next = pos;
	pos->prev = newnode;
	
}
void ListErase(ListNode* pos)
{
	assert(pos);
	assert(pos->next != pos);
	//posprev  pos  posnext

	pos->next->prev = pos->prev;
	pos->prev->next = pos->next;
	free(pos);
	pos = NULL;
}